from __init__ import  log
from symbide.src.parsing import parsers
from executor import Executor as _Executor
from xml.sax.saxutils import escape
from xml.dom import minidom
from gobject import idle_add

class Executor(_Executor):
    def execute(self, input, main=True):
        self.input = input
        if main:
            log.start()
        input.global_namespace.update({'__execute_subinput__': self.__execute_subinput__})
            
        log('<type>Sympy</type>')
        log('<localNamespace>%s</localNamespace>'%escape(str(input.local_namespace)))
        
        commands =  input.getCommands()
        buf = []
        i = 0
        for c in commands:
            buf.append(c)
            buf.append(i)
            i+=1
        buf.pop()
        text = ('%s__execute_subinput__(%s)'*(len(commands)-1)+'%s')%tuple(buf)
        log('<input>%s</input>'%escape(text))
        
        text = parsers['sympy'].parse(text)
        log('<parsing>%s</parsing>'%text)
        
        self._execute_(text, input, main)
        
        text = ''.join(self.ExecutionResults)
        if input.ancestor.identifier!='Input':
            text = text.rstrip(' \n\t')
        log('<executionOutput>%s</executionOutput>'%escape(text))
        
        text = self.replaceObjects(text, input)
        log('<output>%s</output>'%escape(text))
        
        if main:
            DOM = minidom.parseString('<output>%s</output>'%text).documentElement
            idle_add(input.ancestor.call, 'Output', 'setdom', DOM)
            self.input = None
            log.end()
        else:
            return text
        
    def __execute_subinput__(self, pos):
        log('<subinput>')
        result = self.input.subinputs[int(pos)][0].__execute_instantly__()
        log('</subinput>')
        self.input._objects.append('%s'%str(result))
        self.ExecutionResults.append('__objects__[%s]'%str(len(self.input._objects)-1))